package nl.tue.bsdddump;

import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;

import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.core.NewCookie;

import org.codehaus.jackson.jaxrs.JacksonJsonProvider;

import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.config.ClientConfig;
import com.sun.jersey.api.client.config.DefaultClientConfig;
import com.sun.jersey.api.json.JSONConfiguration;

import org.apache.log4j.BasicConfigurator;
import org.apache.log4j.Logger;


public class PeregrineSearchWorker implements Runnable {
	private String searchTerm ="";
	private static List<NewCookie> cookies;
	private static Logger logger = Logger.getLogger(PeregrineSearchWorker.class);
	PeregrineSearchWorker ( String searchTerm, List<NewCookie>cookies){
		//BasicConfigurator.configure();
		this.searchTerm=searchTerm;
		this.cookies = cookies;
	}
	
	public void run()
	{
		ClientConfig clientConfig = new DefaultClientConfig();
		clientConfig.getClasses().add(JacksonJsonProvider.class);
		clientConfig.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE);
		Client client = Client.create(clientConfig);
		//client.getProviders().
		MultivaluedMap formData;
		String s;
		try {
			
			
			
			s = URLEncoder.encode("*","UTF-8");
			WebResource langR = client.resource("http://bsddpilot.catenda.no/api/4.0/IfdConcept/search/"+searchTerm+s);
			//langR=.cookie(cookies.get(0));
			String res =  langR.accept(MediaType.APPLICATION_JSON_TYPE).cookie(cookies.get(0)).get(String.class);;
			
			if (res.equalsIgnoreCase("null")==false){
				BufferedWriter out = new BufferedWriter(new java.io.OutputStreamWriter(new java.io.FileOutputStream("data/"+searchTerm+".out"),"UTF-8"));
			     out.write("searchResult["+searchTerm+"]:"+res+"\n");
			     logger.info("writing "+"data/"+searchTerm+".out");
	        	 out.flush();
	        	 out.close();
	        	 //System.out.println(res);
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			logger.error("search failed for "+searchTerm+": "+e);
			//e.p
		}
		
		
		
		
	}
	
	
}

